package com.example.mywood;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import bean.ContentDataBean;
import fragment.ApplicationFragment;
import fragment.GoodsFragment;
import fragment.HomeFragment;
import fragment.MyFragment;
import fragment.ZhantingFragment;
import myapp.MyApp;
import myview.AutoScaleTextView;
import util.MyLog;
import util.PermissionUtil;
import util.PreferenceUtil;
import util.RequestManager;
import util.SystemStatusManager;
import util.updateManager;

public class MainActivity extends BaseActivity implements OnPermissionCallback {

    private HomeFragment homeFragment;
    private FragmentManager fragmentManager;
    private List<Fragment> fragments;
    private FragmentTransaction transition;
    private LinearLayout ll_home;
    private ImageView img_home;
    private AutoScaleTextView tv_home;
    private LinearLayout ll_zhanting;
    private ImageView img_zhanting;
    private AutoScaleTextView tv_zhanting;
    private LinearLayout ll_goods;
    private ImageView img_goods;
    private AutoScaleTextView tv_goods;
    private LinearLayout ll_my;
    private ImageView img_my;
    private AutoScaleTextView tv_my;
    private LinearLayout ll_application;
    private ImageView img_application;
    private AutoScaleTextView tv_application;
    private ZhantingFragment zhantingFragment;
    private GoodsFragment goodsFragment;
    private MyFragment myFragment;
    private ApplicationFragment applicationFragment;
    //当前显示的fragment  1是首页  2是展厅  3是商品  4是应用  5是我的
    private String fragmentitem = "1";
    private MyApp myapp;
    private LinearLayout ll_tree_type;
    private ImageView img_tree_type;
    private AutoScaleTextView tv_tree_type;
    private Context context;
    private String apptype;
    private GoodsFragment treeTypeFragment;
    private SharedPreferences sharedPreferences;
    private String textData;
    private String token;
    private int localVersion;
    private updateManager mUpdateManager;
    private ContentDataBean.DataBean textContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        myapp = (MyApp) getApplicationContext();
        myapp.addDestoryActivity(MainActivity.this, "主页面");
        sharedPreferences = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        token = sharedPreferences.getString("token", "");
        apptype = sharedPreferences.getString("apptype", "0");
        textData = sharedPreferences.getString("textData", "");
//        updateManager mUpdateManager = new updateManager(this, 1);
//        mUpdateManager.checkUpdateInfo();
        setTranslucentStatus();
        initView();
        initLin();
        String language = PreferenceUtil.getString("language", "");
        changeLanuaData(language);
        //TODO  暂时屏蔽版本更新
//        updateVersion();
//        getPermission();
        getconfigData();

        fragmentManager = getSupportFragmentManager();
        fragments = new ArrayList<>();

        // 添加首页
        homeFragment = new HomeFragment();
        fragments.add(homeFragment);
        hideOthersFragment(homeFragment, true);

        /**
         * 请求所有必要的权限----原理就是获取清单文件中申请的权限
         */
//        PermissionsManager.getInstance().requestAllManifestPermissionsIfNecessary2(MainActivity.this, new PermissionsResultAction() {
//            @Override
//            public void onGranted() {
//                Toast.makeText(MainActivity.this, "All permissions have been granted", Toast.LENGTH_SHORT).show();
//            }
//
//            @Override
//            public void onDenied(String permission) {
//                Toast.makeText(MainActivity.this, "Permission " + permission + " has been denied", Toast.LENGTH_SHORT).show();
//            }
//        });

        initSdk();
    }

    private void initSdk() {

//        ChatClient.Options options = new ChatClient.Options();
//        //必填项，appkey获取地址：kefu.easemob.com，“管理员模式 > 渠道管理 > 手机APP”页面的关联的“AppKey”
//        options.setAppkey("1493191014068972#kefuchannelapp75159");
//        //必填项，tenantId获取地址：kefu.easemob.com，“管理员模式 > 设置 > 企业信息”页面的“租户ID”
//        options.setTenantId("75159");
//
//        // Kefu SDK 初始化
//        if (!ChatClient.getInstance().init(getApplicationContext(), options)) {
//            return;
//        }
//        // Kefu EaseUI的初始化
//        UIProvider.getInstance().init(getApplicationContext());
        //后面可以设置其他属性


    }

    private void getPermission() {

        XXPermissions.with(this)
                .permission(Permission.READ_PHONE_STATE)
                .permission(Permission.WRITE_EXTERNAL_STORAGE)
//                .permission(Permission.CAMERA)
                .request(this);

    }


    private void initView() {
        ll_home = findViewById(R.id.ll_home);
        img_home = findViewById(R.id.img_home);
        tv_home = findViewById(R.id.tv_home);
        ll_zhanting = findViewById(R.id.ll_zhanting);
        img_zhanting = findViewById(R.id.img_zhanting);
        tv_zhanting = findViewById(R.id.tv_zhanting);
        ll_goods = findViewById(R.id.ll_goods);
        img_goods = findViewById(R.id.img_goods);
        tv_goods = findViewById(R.id.tv_goods);
        ll_application = findViewById(R.id.ll_application);
        img_application = findViewById(R.id.img_application);
        tv_application = findViewById(R.id.tv_application);
        ll_tree_type = findViewById(R.id.ll_tree_type);
        img_tree_type = findViewById(R.id.img_tree_type);
        tv_tree_type = findViewById(R.id.tv_tree_type);
        ll_my = findViewById(R.id.ll_my);
        img_my = findViewById(R.id.img_my);
        tv_my = findViewById(R.id.tv_my);
        textContent = new Gson().fromJson(textData, new TypeToken<ContentDataBean.DataBean>() {
        }.getType());
        if (textContent != null) {
            tv_home.setText(textContent.getHomepage());
            tv_zhanting.setText(textContent.getShowroom());
            tv_goods.setText(textContent.getGoods());
            tv_application.setText(textContent.getApplication());
            tv_tree_type.setText(textContent.getSeeland_product());
            tv_my.setText(textContent.getMy());
        }

        if ("0".equals(apptype)) {
            //木头
            ll_zhanting.setVisibility(View.VISIBLE);
            ll_application.setVisibility(View.VISIBLE);
            ll_tree_type.setVisibility(View.VISIBLE);
        } else if ("1".equals(apptype)) {
            //熙然
            ll_zhanting.setVisibility(View.GONE);
            ll_application.setVisibility(View.GONE);
            ll_tree_type.setVisibility(View.VISIBLE);
        }

        /*if (Build.VERSION.SDK_INT >= 26) {
            TextViewCompat.setAutoSizeTextTypeWithDefaults(tv_home, TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);
            tv_home.setAutoSizeTextTypeUniformWithConfiguration(1, 3, 2, TypedValue.COMPLEX_UNIT_SP);
            TextViewCompat.setAutoSizeTextTypeWithDefaults(tv_zhanting, TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);
            tv_zhanting.setAutoSizeTextTypeUniformWithConfiguration(1, 3, 2, TypedValue.COMPLEX_UNIT_SP);
            TextViewCompat.setAutoSizeTextTypeWithDefaults(tv_goods, TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);
            tv_goods.setAutoSizeTextTypeUniformWithConfiguration(1, 3, 2, TypedValue.COMPLEX_UNIT_SP);
            TextViewCompat.setAutoSizeTextTypeWithDefaults(tv_application, TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);
            tv_application.setAutoSizeTextTypeUniformWithConfiguration(1, 3, 2, TypedValue.COMPLEX_UNIT_SP);
            TextViewCompat.setAutoSizeTextTypeWithDefaults(tv_tree_type, TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);
            tv_tree_type.setAutoSizeTextTypeUniformWithConfiguration(1, 3, 2, TypedValue.COMPLEX_UNIT_SP);
            TextViewCompat.setAutoSizeTextTypeWithDefaults(tv_my, TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);
            tv_my.setAutoSizeTextTypeUniformWithConfiguration(1, 3, 2, TypedValue.COMPLEX_UNIT_SP);
        } else {
            TextViewCompat.setAutoSizeTextTypeWithDefaults(tv_home, TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);
            TextViewCompat.setAutoSizeTextTypeWithDefaults(tv_zhanting, TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);
            TextViewCompat.setAutoSizeTextTypeWithDefaults(tv_goods, TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);
            TextViewCompat.setAutoSizeTextTypeWithDefaults(tv_application, TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);
            TextViewCompat.setAutoSizeTextTypeWithDefaults(tv_tree_type, TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);
            TextViewCompat.setAutoSizeTextTypeWithDefaults(tv_my, TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);

        }*/

    }

    private void initLin() {
        ll_home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /*if (homeFragment == null) {
                    homeFragment = new HomeFragment();
                    fragments.add(homeFragment);
                    hideOthersFragment(homeFragment, true);
                } else {
                    hideOthersFragment(homeFragment, false);
                }*/
                initBotton();
                img_home.setImageResource(R.mipmap.icon_home_check);
                tv_home.setTextColor(Color.parseColor("#000000"));
                hideOthersFragment(homeFragment, false);
                fragmentitem = "1";

            }
        });

        ll_zhanting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initBotton();
                img_zhanting.setImageResource(R.mipmap.icon_zhanting_check);
                tv_zhanting.setTextColor(Color.parseColor("#000000"));
                if (zhantingFragment == null) {
                    zhantingFragment = new ZhantingFragment();
                    fragments.add(zhantingFragment);
                    hideOthersFragment(zhantingFragment, true);
                } else {
                    hideOthersFragment(zhantingFragment, false);
                }
                hideOthersFragment(zhantingFragment, false);
                fragmentitem = "2";

            }
        });
        ll_goods.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initBotton();
                img_goods.setImageResource(R.mipmap.icon_goodscheck);
                tv_goods.setTextColor(Color.parseColor("#000000"));
                if (goodsFragment == null) {
                    goodsFragment = new GoodsFragment();
                    fragments.add(goodsFragment);
                    hideOthersFragment(goodsFragment, true);
                } else {
                    hideOthersFragment(goodsFragment, false);
                }
                hideOthersFragment(goodsFragment, false);
                fragmentitem = "3";

            }
        });
        ll_application.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initBotton();
                img_application.setImageResource(R.mipmap.icon_appli_checked);
                tv_application.setTextColor(Color.parseColor("#000000"));
                if (applicationFragment == null) {
                    applicationFragment = new ApplicationFragment();
                    fragments.add(applicationFragment);
                    hideOthersFragment(applicationFragment, true);
                } else {
                    hideOthersFragment(applicationFragment, false);
                }
                hideOthersFragment(applicationFragment, false);
                fragmentitem = "4";

            }
        });
        ll_my.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initBotton();
                img_my.setImageResource(R.mipmap.icon_my_check);
                tv_my.setTextColor(Color.parseColor("#000000"));

                if (myFragment == null) {
                    myFragment = new MyFragment();
                    fragments.add(myFragment);
                    hideOthersFragment(myFragment, true);
                } else {
                    hideOthersFragment(myFragment, false);
                }
                hideOthersFragment(myFragment, false);
                fragmentitem = "5";
            }
        });
        ll_tree_type.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initBotton();
                img_tree_type.setImageResource(R.mipmap.icon_shuzhong_checked);
                tv_tree_type.setTextColor(Color.parseColor("#000000"));

                if (treeTypeFragment == null) {
                    treeTypeFragment = new GoodsFragment();
                    treeTypeFragment.apptype = "1";
                    fragments.add(treeTypeFragment);
                    hideOthersFragment(treeTypeFragment, true);
                } else {
                    hideOthersFragment(treeTypeFragment, false);
                }
                hideOthersFragment(treeTypeFragment, false);
                fragmentitem = "5";
            }
        });
    }

    private void initBotton() {
        img_home.setImageResource(R.mipmap.icon_home);
        img_zhanting.setImageResource(R.mipmap.icon_zhanting);
        img_goods.setImageResource(R.mipmap.icon_goods);
        img_application.setImageResource(R.mipmap.icon_appli);
        img_my.setImageResource(R.mipmap.icon_my);
        img_tree_type.setImageResource(R.mipmap.icon_shuzhong);
        tv_home.setTextColor(Color.parseColor("#999999"));
        tv_zhanting.setTextColor(Color.parseColor("#999999"));
        tv_goods.setTextColor(Color.parseColor("#999999"));
        tv_application.setTextColor(Color.parseColor("#999999"));
        tv_my.setTextColor(Color.parseColor("#999999"));
        tv_tree_type.setTextColor(Color.parseColor("#999999"));
    }

    /**
     * 动态显示Fragment
     *
     * @param showFragment 要增加的fragment
     * @param add          true：增加fragment；false：切换fragment
     */
    private void hideOthersFragment(Fragment showFragment, boolean add) {
        transition = fragmentManager.beginTransaction();
        if (add)
            transition.add(R.id.main_container_content, showFragment);
        for (Fragment fragment : fragments) {
            if (showFragment.equals(fragment)) {
                transition.show(fragment);
            } else {
                transition.hide(fragment);
            }
        }
        transition.commit();
    }

    /**
     * 设置状态栏背景状态
     */
    public void setTranslucentStatus() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window win = getWindow();
            WindowManager.LayoutParams winParams = win.getAttributes();
            final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            winParams.flags |= bits;
            win.setAttributes(winParams);
        }
        SystemStatusManager tintManager = new SystemStatusManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintResource(0);//状态栏无背景
    }

    private boolean isExit = false;

    /**
     * 连按两次返回退出
     */
    public void doubleClickExit() {
        Timer timer = null;
        if (!isExit) {
            //设置退出条件为true
            isExit = true;
            //提示
            Toast.makeText(this, textContent.getExit(), Toast.LENGTH_SHORT).show();
            //启动计时器  2S内不点退出的话  就重置isExit的状态
            timer = new Timer();

            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;
                }
            }, 2000);
        } else {
            //退出app
            finish();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {

            if (!"1".equals(fragmentitem)) {
                initBotton();
                img_home.setImageResource(R.mipmap.icon_home_check);
                tv_home.setTextColor(Color.parseColor("#000000"));
                hideOthersFragment(homeFragment, false);
                fragmentitem = "1";
            } else {
                doubleClickExit();
            }


        }
        return false;
    }

    /**
     * 获取配置信息
     */
    private void getconfigData() {

        String url = myapp.getWebConfig() + "/api/index/my_config";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_GET, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
//                {"code":1,"msg":"发送成功","time":"1571105679","data":8851}
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
//                        handler.sendMessage(msg);
                        return;
                    }
                    JSONObject data = jsonObject.getJSONObject("data");
                    String domain = data.getString("domain");
                    String urlstr = data.getString("url");
                    String z_about = data.getString("z_about");
                    String j_about = data.getString("j_about");
                    String e_about = data.getString("e_about");
                    String z_formula = data.getString("z_formula");
                    sharedPreferences.edit().putString("domain", domain).commit();
                    sharedPreferences.edit().putString("urlstr", urlstr).commit();
                    sharedPreferences.edit().putString("z_about", z_about).commit();
                    sharedPreferences.edit().putString("e_about", e_about).commit();
                    sharedPreferences.edit().putString("j_about", j_about).commit();
                    sharedPreferences.edit().putString("z_formula", z_formula).commit();
//                    msg.arg1 = 2;
//                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
//                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                Log.e("result-my_config", errorMsg);
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });

    }

    /**
     * 切换语言
     */
    private void changeLanuaData(String type) {
        String yuyan = "";
        if ("zh".equals(type)) {
            yuyan = "0";
        } else if ("en".equals(type)) {
            yuyan = "1";
        } else if ("ja".equals(type)) {
            yuyan = "2";
        }

        String url = myapp.getWebConfig() + "/api/user/changelanguage";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        paramsMap.put("type", yuyan);
        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());

                } catch (JSONException e) {
                    e.printStackTrace();

                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                Log.e("result-changelanguage", errorMsg);
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });
    }

    @SuppressLint("HandlerLeak")
    public Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    break;
                case 1:
                    break;
                case 2:
                    break;
                case 3:

                    break;
                case 11:
                    sharedPreferences.edit().putString("token", "").commit();
                    Intent intent = new Intent(context, LoginActivity.class);
                    context.startActivity(intent);
                    myapp.destoryActivity("主页面");
                    break;
            }
        }
    };

    /**
     * 版本更新
     */
    public void updateVersion() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

        } else {
            checkPermission = true;
        }
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 10);
        } else {
            // 获取到权限，作相应处理
            if (PermissionUtil.CheckLocationPermission(this, AppOpsManager.OPSTR_WRITE_EXTERNAL_STORAGE) == 0) {
                checkPermission = true;
                try {
                    PackageInfo packageInfo = getApplicationContext()
                            .getPackageManager().getPackageInfo(getPackageName(), 0);
                    localVersion = packageInfo.versionCode;
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
                mUpdateManager = new updateManager(this, localVersion, textData);
                mUpdateManager.checkUpdateInfo();
            } else {
                PermissionUtil.showPermissionDialog(this);
            }
        }
    }

    /**
     * 授权回调函数
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        switch (requestCode) {
//            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
//            case 10:
//                if (grantResults.length > 0) {
//                    if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
//                        // 没有获取到权限，做特殊处理
//                        PermissionUtil.showPermissionDialog(this);
//                    } else {
//                        if (PermissionUtil.CheckLocationPermission(this, AppOpsManager.OPSTR_WRITE_EXTERNAL_STORAGE) == 0) {
//                            checkPermission = true;
//                            try {
//                                PackageInfo packageInfo = getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
//                                localVersion = packageInfo.versionCode;
//                            } catch (PackageManager.NameNotFoundException e) {
//                                e.printStackTrace();
//                            }
//                            mUpdateManager = new updateManager(this, localVersion, textData);
//                            mUpdateManager.checkUpdateInfo();
//                        } else {
//                            PermissionUtil.showPermissionDialog(this);
//                        }
//                    }
//                } else {
//                    PermissionUtil.showPermissionDialog(this);
//                }
//                break;
//            default:
//                break;
//        }


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == XXPermissions.REQUEST_CODE) {
            getPermission();
        }
    }

    private boolean checkPermission = false;

    @Override
    protected void onRestart() {
        super.onRestart();
        if (!checkPermission) {
            //TODO   暂时屏蔽版本更新
//            updateVersion();
        }
    }


    @Override
    public void onGranted(List<String> permissions, boolean all) {
        if (all) {

            try {
                PackageInfo packageInfo = getApplicationContext()
                        .getPackageManager().getPackageInfo(getPackageName(), 0);
                localVersion = packageInfo.versionCode;
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            mUpdateManager = new updateManager(this, localVersion, textData);
            mUpdateManager.checkUpdateInfo();
        }
    }

    @Override
    public void onDenied(List<String> permissions, boolean never) {

        if (never) {
//            Toast.makeText(MainActivity.this, "请手动打开文件存储、相机权限", Toast.LENGTH_LONG).show();
            // 如果是被永久拒绝就跳转到应用权限系统设置页面
            //  XXPermissions.startPermissionActivity(MainActivity.this, permissions);

            // 没有获取到权限，做特殊处理
            showPermissionDialog(this, permissions);
        } else {

            getPermission();
        }

    }


    /**
     * 提示打开设置对话框
     */
    private void showPermissionDialog(final Activity activity, List<String> permissions) {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle(activity.getString(R.string.help));
        builder.setMessage(activity.getString(R.string.open_proess));
        // 拒绝, 退出应用
        builder.setNegativeButton(activity.getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
//                activity.finish();
            }
        });

        builder.setPositiveButton(activity.getString(R.string.text_btn_set), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                XXPermissions.startPermissionActivity(activity, permissions);
            }
        });
        builder.setCancelable(false);
        builder.show();
    }
}
